package com.oa.kq.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.mdp.core.err.BizException;
import com.mdp.core.service.BaseService;
import com.mdp.core.service.SequenceService;
import com.mdp.safe.client.entity.User;
import com.mdp.safe.client.utils.LoginUtils;
import com.oa.common.service.SysUserService;
import com.oa.kq.entity.*;
import com.oa.kq.mapper.GroupMapper;
import com.oa.kq.vo.GroupInfoVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author maimeng-mdp code-gen
 * @since 2023年10月9日
 */
@Service
public class GroupService extends BaseService<GroupMapper, Group> {
    static Logger logger = LoggerFactory.getLogger(GroupService.class);

    /**
     * 自定义查询，支持多表关联
     *
     * @param page 分页条件
     * @param ew   一定要，并且必须加@Param("ew")注解
     * @param ext  如果xml中需要根据某些值进行特殊处理，可以通过这个进行传递，非必须，注解也可以不加
     * @return
     */
    public List<Map<String, Object>> selectListMapByWhere(IPage page, QueryWrapper ew, Map<String, Object> ext) {
        return baseMapper.selectListMapByWhere(page, ew, ext);
    }


    @Autowired
    private SequenceService seqService;
    @Autowired
    private GroupResponsibilityService responsiService;
    @Autowired
    private GroupDeptService groupDeptService;
    @Autowired
    private GroupNoAttendanceService groupNoAttendanceService;
    @Autowired
    private GroupOtherAttendanceService groupOtherAttendanceService;
    @Autowired
    private GroupPositionService groupPositionService;
    @Autowired
    private GroupScheduleService groupScheduleService;
    @Autowired
    private GroupScheduleCycleService groupScheduleCycleService;
    @Autowired
    private DeptService deptService;
    @Autowired
    private ScheduleService scheduleService;
    @Autowired
    private GroupWifiService groupWifiService;

    @Autowired
    private SysUserService sysUserService;

    /**
     * 新增考勤组
     *
     * @param groupInfoVo
     */
    public void insertGroupInfo(GroupInfoVo groupInfoVo) {
        User user = LoginUtils.getCurrentUserInfo();
        //查找该用户属于哪个公司
        Dept dept = new Dept();
        dept.setDeptid(user.getDeptid());
        // 查询最顶级部门：公司
//		Dept rootDept = this.selectOne("selectTopDept", dept);
        Dept rootDept = deptService.selectTopDept(dept);
        //1.插入group表
        //System.out.println(group.getGroupName());
        Group group = groupInfoVo.getGroup();
        group.setId(seqService.getTablePK("group", "id"));
        group.setDeptid(rootDept.getDeptid());
        //获取id
        String groupId = group.getId();
        this.insert(group);
        //2.插入参与部门
        //1)删除其他组与之冲突的参与部门
        List<GroupDept> outOfGroupDeptList = groupInfoVo.getOutOfGroupDeptList();
        if (outOfGroupDeptList != null && outOfGroupDeptList.size() > 0) {
            groupDeptService.batchDeleteByDeptid(outOfGroupDeptList);
        }
        List<GroupDept> gDepartList = groupInfoVo.getgDeptList();
        if (gDepartList != null && gDepartList.size() > 0) {
            for (GroupDept gDepart : gDepartList) {
                gDepart.setId(seqService.getTablePK("group_depart", "id"));
                gDepart.setGroupId(groupId);
            }
            groupDeptService.batchInsert(gDepartList);
        }

        //3.无需参与人员
        List<GroupNoAttendance> gNoAttList = groupInfoVo.getgNoAttList();
        if (gNoAttList != null && gNoAttList.size() > 0) {
            for (GroupNoAttendance gNoAtt : gNoAttList) {
                gNoAtt.setId(seqService.getTablePK("group_no_attendance", "id"));
                gNoAtt.setGroupId(groupId);
            }
            groupNoAttendanceService.batchInsert(gNoAttList);
        }

        //4.其他参与人员
        //1)删除其他组与之冲突的考勤人员。
        List<GroupOtherAttendance> outOfGroupAttList = groupInfoVo.getOutOfGroupAttList();
        if (outOfGroupAttList != null && outOfGroupAttList.size() > 0) {
            groupOtherAttendanceService.batchDeleteByUserid(outOfGroupAttList);
        }
        List<GroupOtherAttendance> gOtherAttList = groupInfoVo.getgOtherAttList();
        if (gOtherAttList != null && gOtherAttList.size() > 0) {
            for (GroupOtherAttendance gOtherAtt : gOtherAttList) {
                gOtherAtt.setId(seqService.getTablePK("group_other_attendance", "id"));
                gOtherAtt.setGroupId(groupId);
            }
            groupOtherAttendanceService.batchInsert(gOtherAttList);
        }

        //5.考勤组负责人
        List<GroupResponsibility> gResponList = groupInfoVo.getgResponList();
        if (gResponList != null && gResponList.size() > 0) {
            for (GroupResponsibility gResponsibility : gResponList) {
                gResponsibility.setId(seqService.getTablePK("group_responsibility", "id"));
                gResponsibility.setGroupId(groupId);
            }
            responsiService.batchInsert(gResponList);
        }

        if (group.getKqType().equals("0")) {
            //固定方式
            //6.所选择的考勤时间
            GroupSchedule gSchedule = groupInfoVo.getgSchedule();
            gSchedule.setId(seqService.getTablePK("group_schedule", "id"));
            gSchedule.setGroupId(groupId);
            groupScheduleService.insert(gSchedule);
            //7.考勤周期：日期
            GroupScheduleCycle gScheduleCycle = groupInfoVo.getgScheduleCycle();
            gScheduleCycle.setId(seqService.getTablePK("group_schedule_cycle", "id"));
            gScheduleCycle.setGroupId(groupId);
            groupScheduleCycleService.insert(gScheduleCycle);
        } else if (group.getKqType().equals("1")) {
            //排班方式：暂无
        }
        //7.考勤地点
        List<GroupPosition> gPositionList = groupInfoVo.getgPositionList();
        for (GroupPosition groupPosition : gPositionList) {
            groupPosition.setId(seqService.getTablePK("group_position", "id"));
            groupPosition.setGroupId(groupId);
        }
        groupPositionService.batchInsert(gPositionList);

    }


    /**
     * 添加考勤组拓展
     *
     * @author LinYuKun
     * @cdate 2020/1/7 14:43
     */
    public void insertGroupInfoExt(GroupInfoVo groupInfoVo) {
        Group group = groupInfoVo.getGroup();
        group.setId(this.createKey("id"));
        this.insert(group);
        //2.插入参与部门
        //1)删除其他组与之冲突的参与部门
        List<GroupDept> outOfGroupDeptList = groupInfoVo.getOutOfGroupDeptList();
        if (outOfGroupDeptList != null && outOfGroupDeptList.size() > 0) {
            groupDeptService.batchDeleteByDeptid(outOfGroupDeptList);
        }
        List<GroupDept> gDepartList = groupInfoVo.getgDeptList();
        if (gDepartList != null && gDepartList.size() > 0) {
            for (GroupDept gDepart : gDepartList) {
                gDepart.setId(groupDeptService.createKey("id"));
                gDepart.setGroupId(group.getId());
                groupDeptService.insert(gDepart);
            }
        }

        //3.无需参与人员
        List<GroupNoAttendance> gNoAttList = groupInfoVo.getgNoAttList();
        if (gNoAttList != null && gNoAttList.size() > 0) {
            for (GroupNoAttendance gNoAtt : gNoAttList) {
                gNoAtt.setId(groupNoAttendanceService.createKey("id"));
                gNoAtt.setGroupId(group.getId());
//                groupNoAttendanceService.insert(gNoAttList);
                groupNoAttendanceService.insert(gNoAtt);
            }
        }

        //4.其他参与人员
        //1)删除其他组与之冲突的考勤人员。
        List<GroupOtherAttendance> outOfGroupAttList = groupInfoVo.getOutOfGroupAttList();
        if (outOfGroupAttList != null && outOfGroupAttList.size() > 0) {
            groupOtherAttendanceService.batchDeleteByUserid(outOfGroupAttList);
        }
        List<GroupOtherAttendance> gOtherAttList = groupInfoVo.getgOtherAttList();
        if (gOtherAttList != null && gOtherAttList.size() > 0) {
            for (GroupOtherAttendance gOtherAtt : gOtherAttList) {
                gOtherAtt.setId(groupOtherAttendanceService.createKey("id"));
                gOtherAtt.setGroupId(group.getId());
                if (!StringUtils.isEmpty(group.getBranchId()) && StringUtils.isEmpty(gOtherAtt.getBranchId())) {
                    gOtherAtt.setBranchId(group.getBranchId());
                }
                groupOtherAttendanceService.insert(gOtherAtt);
            }
        }

        //5.考勤组负责人
        List<GroupResponsibility> gResponList = groupInfoVo.getgResponList();
        if (gResponList != null && gResponList.size() > 0) {
            for (GroupResponsibility gResponsibility : gResponList) {
                gResponsibility.setId(responsiService.createKey("id"));
                gResponsibility.setGroupId(group.getId());
                if (!StringUtils.isEmpty(group.getBranchId()) && StringUtils.isEmpty(gResponsibility.getBranchId())) {
                    gResponsibility.setBranchId(group.getBranchId());
                }
//                responsiService.insert(gResponList);
                responsiService.insert(gResponsibility);
            }
        }
        //插入周期
        GroupScheduleCycle gScheduleCycle = groupInfoVo.getgScheduleCycle();
        if (!ObjectUtils.isEmpty(gScheduleCycle)) {
            gScheduleCycle.setId(groupScheduleCycleService.createKey("id"));
            gScheduleCycle.setGroupId(group.getId());
            if (!StringUtils.isEmpty(group.getBranchId()) && StringUtils.isEmpty(gScheduleCycle.getBranchId())) {
                gScheduleCycle.setBranchId(group.getBranchId());
            }
            groupScheduleCycleService.insert(gScheduleCycle);
        }

        //7.考勤地点
        List<GroupPosition> gPositionList = groupInfoVo.getgPositionList();
        for (GroupPosition groupPosition : gPositionList) {
            groupPosition.setId(groupPositionService.createKey("id"));
            groupPosition.setGroupId(group.getId());
            if (!StringUtils.isEmpty(group.getBranchId()) && StringUtils.isEmpty(groupPosition.getBranchId())) {
                groupPosition.setBranchId(group.getBranchId());
            }
            groupPositionService.insert(groupPosition);
        }

        //8.考勤wifi
        List<GroupWifi> gWifiList = groupInfoVo.getgWifiList();
        for (GroupWifi groupWifi : gWifiList) {
            groupWifi.setId(groupWifiService.createKey("id"));
            groupWifi.setGroupId(group.getId());
            if (!StringUtils.isEmpty(group.getBranchId()) && StringUtils.isEmpty(groupWifi.getBranchId())) {
                groupWifi.setBranchId(group.getBranchId());
            }
            groupWifiService.insert(groupWifi);
        }

    }


    /**
     * 获取考勤组信息
     * 如果该用户为公司老大，那么需要查出所有该公司下的考勤组
     * 该用户为负责人，则只能看到所负责的组。
     *
     * @cdate 2020/1/7 15:43
     * @cauthor LinYuKun
     */
    public List<Map<String, Object>> getGroupInfo() {
        List<Map<String, Object>> groupInfo = new ArrayList<>();
        User user = LoginUtils.getCurrentUserInfo();
        //查找该用户属于哪个公司
        Dept dept = new Dept();
        dept.setDeptid(user.getDeptid());
        // 查询最顶级部门：公司
        //Dept rootDept = this.selectOne("selectTopDept", dept);
        //查找该公司下的所有考勤组
        //Dept dept =new Dept();
        List<Group> allGroup = groupDeptService.selectAllGroup(dept);
        for (int i = 0; i < allGroup.size(); i++) {
            Map<String, Object> map = new HashMap<>();
            map.put("group", allGroup.get(i));
            //1.查找每个group的参与部门
            List<Dept> joinDepts = groupDeptService.selectDeptByGroupId(allGroup.get(i).getId());
            map.put("joinDepts", joinDepts);
            //2.人数
            List<User> allMember = this.getAllMember(allGroup.get(i).getId());
            map.put("allMember", allMember);
            //3.负责人。
            List<User> responsiList = responsiService.selectUserByGroupId(allGroup.get(i).getId());
            map.put("responsiList", responsiList);
            //4.考勤时间
		   /* Schedule schedule = scheduleService.selectOne("selectByGroupId",  allGroup.get(i).getId());
		    map.put("schedule", schedule);*/
            //5.考勤日期
            GroupScheduleCycle schCycle = groupScheduleCycleService.selectSchCycleByGroupId(allGroup.get(i).getId());
            map.put("schCycle", schCycle);
            //6.考勤地点
            List<GroupPosition> poiList = groupPositionService.selectPoiByGroupId(allGroup.get(i).getId());
            map.put("poiList", poiList);
            groupInfo.add(map);
        }

        return groupInfo;
    }

    /**
     * 查找group中包含 的员工。
     * 思路：1.获取当前考勤组的考勤人员（参与部门）-减去-其他考勤组的其他考勤人员。
     * 2.获取当前考勤组的其他参与人员
     * 3.获取其他考勤组的考勤人员(参与部门中的)
     * 4.获取当前考勤组无需参与人员
     * <p>
     * 公式=1-3+2-4
     *
     * @return
     */
    public List<User> getAllMember(String groupId) {
        //1.获取当前考勤组的考勤人员（参与部门）-减去-其他考勤组的其他考勤人员。
        List<User> users = groupDeptService.selectKQUserByGroupId(groupId);
        //2.获取当前考勤组的其他参与人员
        List<User> otherUsers = groupOtherAttendanceService.selectOtherUserByGroupId(groupId);
        //3.获取其他考勤组的考勤人员(参与部门中的)
        List<User> otherDeptUsers = groupDeptService.selectOtherGroupUserByGroupId(groupId);
        //4.获取当前考勤组无需参与人员
        List<User> notUsers1 = groupNoAttendanceService.selectNotUserByGroupId(groupId);
        Map<String, User> usersMap = new HashMap<String, User>();
        Map<String, User> notUserMap = new HashMap<String, User>();
        Map<String, User> otherDeptUserMap = new HashMap<String, User>();
        List<User> finalUsers = new ArrayList<User>();//存放该组最终需要考勤的人员
        //3
        for (Iterator iterator = otherDeptUsers.iterator(); iterator.hasNext(); ) {
            User user = (User) iterator.next();
            otherDeptUserMap.put(user.getUserid(), user);
        }
        //1-3
        for (Iterator iterator = users.iterator(); iterator.hasNext(); ) {
            User user = (User) iterator.next();
            if (otherDeptUserMap.containsKey(user.getUserid())) {
                iterator.remove();
            }
        }
        //1：赋值给userMap
        for (Iterator iterator = users.iterator(); iterator.hasNext(); ) {
            User user = (User) iterator.next();
            usersMap.put(user.getUserid(), user);
        }
        //1-3+2
        for (Iterator iterator = otherUsers.iterator(); iterator.hasNext(); ) {
            User user = (User) iterator.next();
            if (!usersMap.containsKey(user.getUserid())) {
                users.add(user);
            }
        }

        //4
        for (Iterator iterator = notUsers1.iterator(); iterator.hasNext(); ) {
            User user = (User) iterator.next();
            notUserMap.put(user.getUserid(), user);
        }
        //1-3+2-4
        for (Iterator iterator = users.iterator(); iterator.hasNext(); ) {
            User user = (User) iterator.next();
            if (!notUserMap.containsKey(user.getUserid())) {
                finalUsers.add(user);
            }
        }
        return finalUsers;
    }

    /**
     * 获取某一组的信息。
     * 包括。group、考勤日期、考勤时间、考勤地点
     *
     * @return
     * @cdate 2020/1/7 16:53
     * @cauthor LinYuKun
     */
    public Map<String, Object> getOneGroupInfo(Group group) {
        Map<String, Object> map = new HashMap<>();
        //1.根据id查找考勤组
        Group getGroup = this.selectOneObject(group);
        map.put("group", getGroup);
        //2.考勤部门
        List<Dept> joinDepts = groupDeptService.selectDeptByGroupId(group.getId());
        map.put("joinDepts", joinDepts);
        //3.无需考勤人员
        List<User> notAttMember = groupNoAttendanceService.selectNotUserByGroupId(group.getId());
        map.put("notAttMember", notAttMember);
        //4.其他考勤人员
        List<User> otherAttMember = groupOtherAttendanceService.selectOtherUserByGroupId(group.getId());
        map.put("otherAttMember", otherAttMember);
        //5.考勤组负责人
        List<User> responsiList = responsiService.selectUserByGroupId(group.getId());
        map.put("responsiList", responsiList);
        //6.考勤时间
        Schedule schedule = scheduleService.selectByGroupId(getGroup.getId());
        map.put("schedule", schedule);
        //7.考勤日期
        GroupScheduleCycle schCycle = groupScheduleCycleService.selectSchCycleByGroupId(getGroup.getId());
        map.put("schCycle", schCycle);
        Set<String> schduleIdSet = new HashSet();
        if (!StringUtils.isEmpty(schCycle.getMonday())) {
            schduleIdSet.add(schCycle.getMonday());
        }
        if (!StringUtils.isEmpty(schCycle.getTuesday())) {
            schduleIdSet.add(schCycle.getTuesday());
        }
        if (!StringUtils.isEmpty(schCycle.getWednesday())) {
            schduleIdSet.add(schCycle.getWednesday());
        }
        if (!StringUtils.isEmpty(schCycle.getThursday())) {
            schduleIdSet.add(schCycle.getThursday());
        }
        if (!StringUtils.isEmpty(schCycle.getFriday())) {
            schduleIdSet.add(schCycle.getFriday());
        }
        if (!StringUtils.isEmpty(schCycle.getSaturday())) {
            schduleIdSet.add(schCycle.getSaturday());
        }
        if (!StringUtils.isEmpty(schCycle.getSunday())) {
            schduleIdSet.add(schCycle.getSunday());
        }
        List<String> schduleList = new ArrayList<>(schduleIdSet);
        List<Map<String, Object>> schedules = new ArrayList();
        if (!ObjectUtils.isEmpty(schduleList)) {
            schedules = scheduleService.selectScheduleByIds(schduleList);
        }
        map.put("schedules", schedules);
        //8.考勤地点
        List<GroupPosition> poiList = groupPositionService.selectPoiByGroupId(getGroup.getId());
        map.put("poiList", poiList);

        //9.wifi
        List<GroupWifi> wifiList = groupWifiService.selectWifiByGroupId(getGroup.getId());
        map.put("wifiList", wifiList);
        return map;
    }

    /**
     * 更新考勤组规则
     *
     * @param groupInfoVo
     */
    public void updateGroupInfo(GroupInfoVo groupInfoVo) {
        User user = LoginUtils.getCurrentUserInfo();
        //查找该用户属于哪个公司
        //Dept dept=new Dept();
        //dept.setDeptid(user.getDeptid());
        // 查询最顶级部门：公司
        //Dept rootDept = this.selectOne("selectTopDept", dept);
        //1.更新group
        Group group = groupInfoVo.getGroup();
        //group.setDeptid(rootDept.getDeptid());
        //获取id
        String groupId = group.getId();
        if (StringUtils.isEmpty(group.getId())) {
            throw new BizException("请传递groupid");
        }
        this.updateByPk(group);
        //2.更新参与部门
        //1)将其他考勤组中的与之冲突的参与部门删掉
        List<GroupDept> outOfGroupDeptList = groupInfoVo.getOutOfGroupDeptList();
        if (outOfGroupDeptList != null && outOfGroupDeptList.size() > 0) {
            groupDeptService.batchDeleteByDeptid(outOfGroupDeptList);
        }
        //2)删除原来的考勤部门。2)再插入
        groupDeptService.deleteJoinDeptByGroupId(groupId);
        List<GroupDept> gDepartList = groupInfoVo.getgDeptList();
        if (gDepartList != null && gDepartList.size() > 0) {
            for (GroupDept gDepart : gDepartList) {
                gDepart.setId(groupDeptService.createKey("id"));
                gDepart.setGroupId(groupId);
                gDepart.setBranchId(group.getBranchId());
                groupDeptService.insert(gDepart);
            }
        }
        //3.无需参与人员
        groupNoAttendanceService.deleteNoAttByGroupId(groupId);
        List<GroupNoAttendance> gNoAttList = groupInfoVo.getgNoAttList();
        if (gNoAttList != null && gNoAttList.size() > 0) {
            for (GroupNoAttendance gNoAtt : gNoAttList) {
                gNoAtt.setId(groupNoAttendanceService.createKey("id"));
                gNoAtt.setGroupId(groupId);
                gNoAtt.setBranchId(group.getBranchId());
//                groupNoAttendanceService.insert(gNoAttList);
                groupNoAttendanceService.insert(gNoAtt);
            }
        }

        //4.其他参与人员
        //1)删除其他组与之冲突的考勤人员。
        List<GroupOtherAttendance> outOfGroupAttList = groupInfoVo.getOutOfGroupAttList();
        if (outOfGroupAttList != null && outOfGroupAttList.size() > 0) {
            groupOtherAttendanceService.batchDeleteByUserid(outOfGroupAttList);
        }
        //2)删除原来的数据，插入数据
        groupOtherAttendanceService.deleteOtherAttByGroupId(groupId);
        List<GroupOtherAttendance> gOtherAttList = groupInfoVo.getgOtherAttList();
        if (gOtherAttList != null && gOtherAttList.size() > 0) {
            for (GroupOtherAttendance gOtherAtt : gOtherAttList) {
                gOtherAtt.setId(groupOtherAttendanceService.createKey("id"));
                gOtherAtt.setGroupId(groupId);
                gOtherAtt.setBranchId(group.getBranchId());
                groupOtherAttendanceService.insert(gOtherAtt);
            }

        }

        //5.考勤组负责人
        responsiService.deleteRespsonByGroupId(groupId);
        List<GroupResponsibility> gResponList = groupInfoVo.getgResponList();
        if (gResponList != null && gResponList.size() > 0) {
            for (GroupResponsibility gResponsibility : gResponList) {
                gResponsibility.setId(responsiService.createKey("id"));
                gResponsibility.setGroupId(groupId);
                gResponsibility.setBranchId(group.getBranchId());
                responsiService.insert(gResponsibility);
            }
        }

        groupScheduleCycleService.deleteGroupScheduleCycleByGroupId(groupId);
        //插入周期
        GroupScheduleCycle gScheduleCycle = groupInfoVo.getgScheduleCycle();
        if (!ObjectUtils.isEmpty(gScheduleCycle)) {
            gScheduleCycle.setId(groupScheduleCycleService.createKey("id"));
            gScheduleCycle.setGroupId(group.getId());
            gScheduleCycle.setBranchId(group.getBranchId());
            groupScheduleCycleService.insert(gScheduleCycle);
        }

        //7.考勤地点
        groupPositionService.deletePoiByGroupId(groupId);
        List<GroupPosition> gPositionList = groupInfoVo.getgPositionList();
        for (GroupPosition groupPosition : gPositionList) {
            groupPosition.setId(groupPositionService.createKey("id"));
            groupPosition.setGroupId(groupId);
            groupPosition.setBranchId(group.getBranchId());
            groupPositionService.insert(groupPosition);
        }

        groupWifiService.deleteWifiByGroupId(groupId);
        List<GroupWifi> gWifiList = groupInfoVo.getgWifiList();
        for (GroupWifi groupWifi : gWifiList) {
            groupWifi.setId(groupWifiService.createKey("id"));
            groupWifi.setGroupId(group.getId());
            if (!StringUtils.isEmpty(group.getBranchId()) && StringUtils.isEmpty(groupWifi.getBranchId())) {
                groupWifi.setBranchId(group.getBranchId());
            }
            groupWifiService.insert(groupWifi);
        }

    }

    /**
     * 获取除了本身，其他组的参与部门：用于修改考勤组时限制
     *
     * @param groupId
     * @return
     */
    public List<Dept> getOtherGroupJoinDept(String groupId) {
        return groupDeptService.selectOtherGroupDeptByGroupId(groupId);
    }

    /**
     * 获取该公司下所有考勤组的参与部门。用于添加考勤组时限制
     *
     * @return
     */
    public List<Dept> getGroupJoinDept() {
        User user = LoginUtils.getCurrentUserInfo();
        //查找该用户属于哪个公司
        Dept dept = new Dept();
        dept.setDeptid(user.getDeptid());
        // 查询最顶级部门：公司
//        Dept rootDept = this.selectOne("selectTopDept", dept);
        Dept rootDept = deptService.selectTopDept(dept);
        //查找该公司下所有考勤组的参与部门
        return groupDeptService.selectGroupsDept(rootDept);
    }

    /**
     * 获取处了本身，其他组参与考勤的人员：用于修改考勤组时限制
     *
     * @param groupId
     * @return
     */
    public List<User> getAllOtherMember(String groupId) {
        //获取其他组id
        List<Group> selectList = groupDeptService.selectOtherGroupByGroupId(groupId);
        List<User> allMember = new ArrayList<>();
        for (int i = 0; i < selectList.size(); i++) {
            List<User> oneGroupMembers = this.getAllMember(selectList.get(i).getId());
            allMember.addAll(oneGroupMembers);
        }
        return allMember;
    }

    /**
     * 获取所有考勤组参与考勤的人员：用于添加考勤组时限制
     *
     * @return
     */
    public List<User> getGroupsMember() {
        //获取所有组id
        User user = LoginUtils.getCurrentUserInfo();
        //查找该用户属于哪个公司
        Dept dept = new Dept();
        dept.setDeptid(user.getDeptid());
        // 查询最顶级部门：公司
//        Dept rootDept = this.selectOne("selectTopDept", dept);
        Dept rootDept = deptService.selectTopDept(dept);
        //查找该公司下的所有考勤组
        List<Group> allGroup = groupDeptService.selectAllGroup(rootDept);
        List<User> allMember = new ArrayList<>();
        for (int i = 0; i < allGroup.size(); i++) {
            List<User> oneGroupMembers = this.getAllMember(allGroup.get(i).getId());
            allMember.addAll(oneGroupMembers);
        }
        return allMember;
    }

    /**
     * 删除考勤组
     *
     * @return
     */
    public void deleteGroup(Group group) {
        if (StringUtils.isEmpty(group.getId())) {
            throw new BizException("请传递groupId");
        }
        //1.删除group
        this.deleteByPk(group);
        //获取id
        String groupId = group.getId();
        //2.删除参与部门
        groupDeptService.deleteJoinDeptByGroupId(groupId);
        //3.无需参与人员
        groupNoAttendanceService.deleteNoAttByGroupId(groupId);
        //4.其他参与人员
        groupOtherAttendanceService.deleteOtherAttByGroupId(groupId);
        //5.考勤组负责人
        responsiService.deleteRespsonByGroupId(groupId);
        groupScheduleCycleService.deleteGroupScheduleCycleByGroupId(groupId);
		/*if(group.getKqType().equals("0")){
		    //固定方式
		    //6.所选择的考勤时间
			groupScheduleService.delete("deleteGScheduleByGroupId", groupId);
		    //7.考勤周期：日期

		 }else if(group.getKqType().equals("1")){
		     //排班方式：暂无
		 }*/
        //7.考勤地点
        groupPositionService.deletePoiByGroupId(groupId);
        //8.删除wifi
        groupWifiService.deleteWifiByGroupId(groupId);
    }

    /**
     * 根据用户查询其所在的考勤组
     *
     * @return 查询这个用户属于哪个外勤组
     * 如果有外勤组 那么获取出来，看这个外勤组的固定的排班时间表
     * 1.查看用户所属的组
     * 2.查看用户所属的组的排版时间表
     * 3.查看这个排版时间表的规则
     */
    public Map<String, Object> getGroupByUser(User user, String date) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Map<String, Object> map = new HashMap<>();
        Date getDate;
        Schedule schedule = null;
        Group group = null;
        try {
            getDate = sdf.parse(date);//转换日期
            //查看kq_group 表  根据userid 以及部门 或者是这个人所在的部门有考勤组就可以了
            group = this.selectGroupByUseridAndDeptid(user.getUserid(), user.getDeptid());
            if (group != null) {
                if (group.getKqType().equals("0")) {//固定
                    Calendar c = Calendar.getInstance();
                    c.setTime(getDate);
                    int weekday = c.get(Calendar.DAY_OF_WEEK);//1星期日2星期一
                    GroupScheduleCycle schCycle = groupScheduleCycleService.selectSchCycleByGroupId(group.getId());
                    //周日
                    String schId = new String();
                    if (weekday == 1) {//周日
                        schId = schCycle.getSunday();
                    } else if (weekday == 2) {//周一
                        schId = schCycle.getMonday();
                    } else if (weekday == 3) {//周二
                        schId = schCycle.getTuesday();
                    } else if (weekday == 4) {//周三
                        schId = schCycle.getWednesday();
                    } else if (weekday == 5) {//周四
                        schId = schCycle.getThursday();
                    } else if (weekday == 6) {//周五
                        schId = schCycle.getFriday();
                    } else if (weekday == 7) {//周六
                        schId = schCycle.getSaturday();
                    }
                    Schedule schCondition = new Schedule();
                    schCondition.setId(schId);
                    schedule = scheduleService.selectOneObject(schCondition);
                } else if (group.getKqType().equals("1")) {//排班

                } else if (group.getKqType().equals("2")) {//自由
                    //自由，没有考勤规则
                }
            }
            map.put("schedule", schedule);
            map.put("group", group);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return map;
    }


    public Map<String, Object> getGroupByPage(Map<String, Object> params) {
        Map<String, Object> map = new HashMap<>();
        try {
            Integer pagesize = Integer.valueOf((String) params.get("pagesize"));
            Integer pageno = Integer.valueOf((String) params.get("pageno"));


            Integer startIndex = (pageno - 1) * pagesize;
            params.put("startIndex", startIndex);
            params.put("pagesize", pagesize);
//            List<Group> groupList = this.selectList("selectGroupByPage", params);
            List<Group> groupList = baseMapper.selectGroupByPage(params);
//            Integer total = this.selectOne("selectGroupByCount", params);
            Integer total = baseMapper.selectGroupByCount(params);
            map.put("groupList", groupList);
            map.put("pageNum", pageno);
            map.put("pageSize", pagesize);
            map.put("total", total);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }

    public Group selectGroupByUseridAndDeptid(String userid, String deptid) {
        List<String> deptids = new ArrayList<>();
        if (StringUtils.hasText(deptid)) {
            deptids = this.sysUserService.getSubDeptidsByDeptid(deptid);
        }
        Map<String, Object> params = new HashMap<>();
        if (deptids != null && deptids.size() > 0) {
            params.put("deptids", deptids);
        }
        params.put("userid", userid);
        List<Group> groups = baseMapper.selectGroupByUseridAndDeptids(params);
        if (groups == null || groups.size() == 0) {
            return null;
        } else {
            return groups.get(0);
        }
    }
}

